import { getDstPSAppDEAction, IPSDEDEActionLogic, IPSDELogicParam } from '@ibiz/dynamic-model-api';
import { AppDeLogicNodeBase } from './logic-node-base';
import { ActionContext } from '../action-context';
import { LogUtil, Util } from '../../../utils';

/**
 * 实体行为处理节点
 *
 * @export
 * @class AppDeLogicDeActionNode
 */
export class AppDeLogicDeActionNode extends AppDeLogicNodeBase {

    constructor() {
        super();
    }

    /**
     * 执行节点
     *
     * @static
     * @param {IPSDELogicNode} logicNode 逻辑节点
     * @param {ActionContext} actionContext 逻辑上下文
     * @memberof AppDeLogicDeActionNode
     */
    public async executeNode(logicNode: IPSDEDEActionLogic, actionContext: ActionContext) {
        try {
            await this.handleDEAction(logicNode, actionContext);
            return this.computeNextNodes(logicNode, actionContext);
        } catch (error: any) {
            LogUtil.error(`逻辑节点${logicNode.name}${error?.message ? error?.message : '发生未知错误！'}`);
        }
    }

    /**
     * 处理实体行为
     *
     * @private
     * @param {IPSDEDEActionLogic} logicNode
     * @param {ActionContext} actionContext
     * @memberof AppDeLogicDeActionNode
     */
    private async handleDEAction(logicNode: IPSDEDEActionLogic, actionContext: ActionContext) {
        const dstEntity = logicNode.getDstPSAppDataEntity();
        const deAction = await getDstPSAppDEAction(logicNode);
        const dstParam = actionContext.getParam((logicNode.getDstPSDELogicParam() as IPSDELogicParam)?.codeName);
        const retParam = actionContext.getParam((logicNode.getRetPSDELogicParam() as IPSDELogicParam)?.codeName);
        if (dstEntity && deAction && dstParam) {
            try {
                const service = await ___ibz___.gs.getService(dstEntity.codeName);
                const tempContext = Util.deepCopy(actionContext.context);
                if(dstParam.getReal()){
                    Object.assign(tempContext, dstParam.getReal());
                }
                const res = await service[deAction.codeName](tempContext, dstParam.getReal() ? dstParam.getReal() : {});
                if (res && res.ok && res.data) {
                    if(retParam){
                        retParam.bind(res.data);
                    }
                    actionContext.bindLastReturnParam(res.data);
                } else {
                    throw new Error(`执行实体行为失败`);
                }
            } catch (error) {
                throw new Error(`执行实体行为失败`);
            }
        } else {
            throw new Error(`执行实体行为所需参数不足`);
        }
    }
}